<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/axios'

interface User {
  id: number
  username: string
  realName: string
  phone: string | null
  email: string | null
  userType: number
  status: number
  createTime: string
}

const tableData = ref<User[]>([])
const loading = ref(false)
const total = ref(0)

const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const searchForm = ref({
  username: '',
  realName: '',
  phone: '',
  userType: null,
  status: null
})

// 获取用户列表数据
const fetchUsers = async () => {
  try {
    loading.value = true
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }
    const { data } = await request.get('/users/page', { params })
    tableData.value = data.data.records
    total.value = data.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error('获取用户列表失败：', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

const handleReset = () => {
  searchForm.value = {
    username: '',
    realName: '',
    phone: '',
    userType: null,
    status: null
  }
  currentPage.value = 1
  fetchUsers()
}

// 监听分页变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUsers()
}

// 详情弹窗相关
const detailVisible = ref(false)
const currentUser = ref<User>()

// 编辑弹窗相关
const editVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref<User>({
  id: 0,
  username: '',
  realName: '',
  phone: '',
  email: '',
  userType: 2,
  status: 1,
  createTime: ''
})

const rules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

const handleViewDetail = (row: User) => {
  currentUser.value = row
  detailVisible.value = true
}

const handleEdit = (row: User) => {
  editForm.value = { ...row }
  editVisible.value = true
}

const handleDelete = (row: User) => {
  // TODO: 实现删除功能
}

const handleEditSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      // TODO: 提交编辑
      editVisible.value = false
    }
  })
}

const addVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = ref<Omit<User, 'id' | 'createTime'>>({
  username: '',
  realName: '',
  phone: '',
  email: '',
  userType: 2,
  status: 1
})

const handleAdd = () => {
  addVisible.value = true
}

const handleAddSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        await request.post('/users/add', addForm.value)
        ElMessage.success('添加用户成功')
        addVisible.value = false
        fetchUsers()
        // 重置表单
        addForm.value = {
          username: '',
          realName: '',
          phone: '',
          email: '',
          userType: 2,
          status: 1
        }
      } catch (error) {
        ElMessage.error('添加用户失败')
        console.error('添加用户失败：', error)
      }
    }
  })
}

onMounted(() => {
  fetchUsers()
})
</script>

<template>
  <!-- 添加用户弹窗 -->
  <el-dialog v-model="addVisible" title="添加用户" width="40%" :before-close="() => addVisible = false">
    <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username" />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="addForm.realName" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="addForm.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email" />
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="addForm.userType" placeholder="请选择用户类型">
          <el-option label="管理员" :value="0" />
          <el-option label="咨询师" :value="1" />
          <el-option label="普通用户" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="addForm.status" placeholder="请选择状态">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAddSubmit(addFormRef)">保存</el-button>
    </template>
  </el-dialog>

  <!-- 详情弹窗 -->
  <el-dialog v-model="detailVisible" title="用户详情" width="50%" :before-close="() => detailVisible = false">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="用户名">
        {{ currentUser?.username }}
      </el-descriptions-item>
      <el-descriptions-item label="真实姓名">
        {{ currentUser?.realName }}
      </el-descriptions-item>
      <el-descriptions-item label="手机号">
        {{ currentUser?.phone || '未设置' }}
      </el-descriptions-item>
      <el-descriptions-item label="邮箱">
        {{ currentUser?.email || '未设置' }}
      </el-descriptions-item>
      <el-descriptions-item label="用户类型">
        {{ currentUser?.userType === 0 ? '管理员' : currentUser?.userType === 1 ? '咨询师' : '普通用户' }}
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentUser?.status === 1 ? 'success' : 'danger'" effect="dark">
          {{ currentUser?.status === 1 ? '正常' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ currentUser?.createTime }}
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>

  <!-- 编辑弹窗 -->
  <el-dialog v-model="editVisible" title="编辑用户" width="40%" :before-close="() => editVisible = false">
    <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="editForm.realName" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editForm.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" />
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="editForm.userType" placeholder="请选择用户类型">
          <el-option label="管理员" :value="0" />
          <el-option label="咨询师" :value="1" />
          <el-option label="普通用户" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="editForm.status" placeholder="请选择状态">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editVisible = false">取消</el-button>
      <el-button type="primary" @click="handleEditSubmit(editFormRef)">保存</el-button>
    </template>
  </el-dialog>

  <div class="users-container">
    <div class="header">
      <h2>用户管理</h2>
    </div>
    <div class="search-area">
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="searchForm.realName" placeholder="请输入真实姓名" clearable />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item label="用户类型">
            <el-select v-model="searchForm.userType" placeholder="请选择用户类型" clearable>
              <el-option label="管理员" :value="0" />
              <el-option label="咨询师" :value="1" />
              <el-option label="普通用户" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">添加用户</el-button>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="ID" min-width="80" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="realName" label="真实姓名" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="120">
          <template #default="{ row }">
            {{ row.phone || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180">
          <template #default="{ row }">
            {{ row.email || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="userType" label="用户类型" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.userType === 0 ? '管理员' : row.userType === 1 ? '咨询师' : '普通用户' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
        <el-table-column label="操作" min-width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          :page-sizes="[10, 20, 30, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.users-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.table-container {
  position: relative;
}

.table-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
